﻿using System;
using System.Collections.Generic;
using IrrlichtLime;
using IrrlichtLime.Core;
using Timed;
using IrrlichtLime.Scene;
using IrrlichtLime.Video;
using Iso;
using AForge.Video.FFMPEG;
using Iso.Common;

namespace Game.Plugin
{
    public class VideoPlayer : IScene
    {
        VideoFileReader reader;
        string filename, onEnd;
        
        public VideoPlayer(string filename, string onEnd)
        {
            this.filename = filename;
            this.onEnd = onEnd;
        }

        public void Load()
        {
            reader = new VideoFileReader();
            reader.Open(filename);
            for (int i = 0; i < reader.FrameCount; i++)
            {
                Engine.timeline.operations.Add(new TimedOperation(Engine.currentTime + (uint)i * (1000 / (uint)reader.FrameRate),
                    new EventHandler<TimedEventArgs>((object sender, TimedEventArgs args) =>
                    {
                        Engine.device.VideoDriver.BeginScene();
                        Texture tex = reader.ReadVideoFrame().BitmapToTexture();
                        Engine.device.VideoDriver.Draw2DImage(tex, Engine.device.VideoDriver.ViewPort, new Recti(0, 0, tex.Size.Width, tex.Size.Height));
                        Engine.device.VideoDriver.EndScene();
                    })));
            }
            Engine.timeline.operations.Add(new TimedOperation(Engine.currentTime + (uint)reader.FrameCount * (1000 / (uint)reader.FrameRate),
                    new EventHandler<TimedEventArgs>((object sender, TimedEventArgs args) =>
                    {
                        LuaInterface.LuaFunction f = Engine.lua.GetFunction(onEnd);
                        if (f != null)
                            f.Call();
                    })));
        }

        public void Unload()
        {

        }

        public void Update()
        {

        }

        public void Draw()
        {

        }
    }
}
